const config = require('./app/config/config');
const koa = require('koa');
const path = require("path");

const http = require('http');
const https = require('https');
const views = require('koa-views');

const log4js = require('koa-log4');

const koaBody = require('koa-body');

log4js.configure(path.join(__dirname, 'log4js.json'), {
    cwd: config.logDir
});

const  logger = log4js.getLogger("app");

const app = new koa();
app.use(koaBody({multipart: true}));
app.use(function* (next) {
    //config 注入中间件，方便调用配置信息
    if (!this.config) {
        this.config = config;
    }
    if(!this.logger) {
        this.logger = logger;
    }
    yield next;
});

app.use(views(config.viewDir, {
    extension: 'html'
}));

const koaStatic = require('koa-static');

app.use(koaStatic(config.staticDir));

const Router = require('koa-router');


let home = require('./app/router/index')(new Router());

let mount = require('koa-mount');

app.use(mount('/', home.middleware()));

app.on('error', async (err, ctx)=> {
    console.error('----------------------------------------');
    console.error(err);
    console.error('----------------------------------------');
});

http.createServer(app.callback()).listen(config.port.http, ()=> {
    console.log('listening on port %s', config.port.http);
});
https.createServer(app.callback()).listen(config.port.https, ()=> {
    console.log('listening on port %s', config.port.https);
});

// app.listen(config.port, () => {
//     console.log('listening on port %s', config.port);
// });

module.exports = app;